package cn.datastruct.four;

//构造学生数据类型
class DoubleLinkedNode {
    //成员变量
    public int age;
    public String name;
    public String id;
    public DoubleLinkedNode next;//指向后一个
    public DoubleLinkedNode pre;//指向前一个一个

    //构造函数
    public DoubleLinkedNode(int age, String name, String id) {
        this.age = age;
        this.name = name;
        this.id = id;
    }

    //重写toString()
    @Override
    public String toString() {
        return "DoubleLinkedNode{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
    }
}

/*
    双向链表：
        1、求链表长度，size()
        1、实现add(DoubleLinkedNode dln)函数
        2、实现del()函数
        3、insert(DoubleLinkedNode dln, int index),删除指定位置元素
        4，show(),打印链表
* */
public class DoubleLinkedList {
    public DoubleLinkedNode dll;

    //构造
    public DoubleLinkedList() {
        this.dll = new DoubleLinkedNode(-1, "", "");
    }

    //1,求链表长度size()
    public int size() {
        DoubleLinkedNode temp = this.dll.next;
        int length = 0;
        while (temp != null) {
            temp = temp.next;//往后移动一个对象
            length++;
        }
        return length;
    }

    //2、实现add(DoubleLinkedNode dln)函数
    public void insert(DoubleLinkedNode dln) {
        DoubleLinkedNode temp = this.dll;
        while (temp.next != null) {
            temp = temp.next;//往后移动一个对象
        }
        temp.next = dln;
        dln.pre = temp;
    }

    //3、指定位置插入元素
    public void insertByIndex(DoubleLinkedNode dln, int index) {
        DoubleLinkedNode temp = this.dll;
        //判断index是否越界
        int length = this.size();
        if (index <= 0 || index > length)
            return;
        //找到index,让temp指向该位置
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        //添加元素
        temp.pre.next = dln;
        dln.pre = temp.pre;
        temp.pre = dln;
        dln.next = temp;
    }

    //3、实现del()函数
    public void del() {
        //判断有无元素
        if (size() == 0)
            return;
        DoubleLinkedNode temp = this.dll;
        //移动到最后
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.pre.next = null;

    }
    //4、delByIndex(int index),删除指定位置元素
    public void delByIndex(int index){
        DoubleLinkedNode temp = this.dll;
        //判断index是否越界
        int length = this.size();
        if (index <= 0 || index > length)
            return;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        temp.next.pre = temp.pre;
        temp.pre.next = temp.next;
    }
    //5，show(),打印链表
    public void showDoubleLinkedList(){
        DoubleLinkedNode temp = this.dll.next;
        //判断index是否越界
        int length = this.size();
        if (length == 0)
            System.out.println("此链表为空");
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }
}
